package com.station.xml;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;


/**
 * 实现对象属性的表单展示名称和值的映射关系的存储，方便后续动态创建表单布局
 * 
 * @author hehc
 * 
 */
public abstract class KVSupport {

	private HashMap<String, KV> kvMaps = new HashMap<String, KV>(0);

	private List<KV> kvs = new ArrayList<KV>(0);

	// 反射当前对象，将标注了 kv=true 的字段存入映射表
	public List<KV> getKvs() {
		return kvs;
	}

	public void setKvs(List<KV> kvs) {
		this.kvs = kvs;
	}

	public void kvInject() {
		Field[] flds = this.getClass().getDeclaredFields();
		for (Field fld : flds) {
			if (!fld.isAnnotationPresent(AnGetfunc.class)) {
				continue;
			}
			AnGetfunc axh = fld.getAnnotation(AnGetfunc.class);
			if (axh.need() && axh.kv()) {
				try {
					kvMaps.put(String.valueOf(axh.kvIndex()), new KV(
							axh.name(), fld.get(this)));
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}
		List<String> arrayList = new ArrayList<String>(kvMaps.keySet());
		Collections.sort(arrayList, new Comparator<String>() {
			@Override
			public int compare(String lhs, String rhs) {
				return Integer.valueOf(lhs).intValue()
						- Integer.valueOf(rhs).intValue();
			}
		});
		for(int i=0,s=arrayList.size(); i<s; i++){
			kvs.add(kvMaps.get(arrayList.get(i)));
		}

	};

}
